package cc.eddic.practice.concurrency.impl;

import cc.eddic.practice.concurrency.CdnLogItem;
import cc.eddic.practice.concurrency.CdnLogItemParser;
import cc.eddic.practice.concurrency.LogItem;
import cc.eddic.practice.concurrency.LogItemParser;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CdnLogItemParserImpl implements CdnLogItemParser {
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("dd/MMM/yyyy:HH:mm:ss Z", Locale.ENGLISH);

    @Override
    public Optional<CdnLogItem> parse(String logLine) {
        Pattern pattern =  Pattern.compile("(?<clientIP>.+) (?<hitMiss>.+) (?<responseTime>\\d+) \\[(?<timeZone>.+)] \"(?<method>\\w+) (?<url>.+) (?<protocol>\\S+?)\" (?<statusCode>\\d+) (?<trafficSize>\\d+) \"(?<referer>.*?)\" \"(?<userAgent>.*)\"", Pattern.UNICODE_CHARACTER_CLASS | Pattern.DOTALL);
        Matcher matcher = pattern.matcher(logLine);
        if (matcher.find()) {
            String clientIP = matcher.group("clientIP");
            String hitMiss = matcher.group("hitMiss");
            int responseTime = Integer.parseInt(matcher.group("responseTime"));
            LocalDateTime timeZone = LocalDateTime.parse(matcher.group("timeZone"), DATE_TIME_FORMATTER);

            String method = matcher.group("method");
            String url = matcher.group("url");
            String protocol = matcher.group("protocol");

            int statusCode = Integer.parseInt(matcher.group("statusCode"));
            long trafficSize = Long.parseLong(matcher.group("trafficSize"));
            String referer = matcher.group("referer");
            String userAgent = matcher.group("userAgent");

            return Optional.of(new CdnLogItem(clientIP, hitMiss, responseTime, timeZone, method, url, null, protocol, statusCode, trafficSize, referer, userAgent));
        }

        return Optional.empty();
    }

}